package com.ganzalang.gmall.promotion.service.rule.condition.composite;

import com.ganzalang.gmall.promotion.dto.EnjoyConditionResult;
import com.ganzalang.gmall.promotion.dto.TargetResult;

import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @author: Ganzalang
 * @Date 2022/4/11 17:46
 */
public class Composite extends Component{

    /**
     * 构件容器
     */
    private List<Component> componentArrayList = new ArrayList();

    /**
     * 增加一个叶子构件或树枝构件
     *
     * @param component
     */
    public void add(Component component){
        this.componentArrayList.add(component);
    }

    /**
     * 删除一个叶子构件或树枝构件
     *
     * @param component
     */
    public void remove(Component component){
        this.componentArrayList.remove(component);
    }

    /**
     * 获得分支下的所有叶子构件和树枝构件
     *
     * @return
     */
    public List getChildren(){
        return this.componentArrayList;
    }

    /**
     * 判断是否满足促销活动的条件
     *
     * @param context
     * @return
     */
    @Override
    public EnjoyConditionResult validate(TargetResult context) {
        EnjoyConditionResult result = new EnjoyConditionResult();

        for (Component component : componentArrayList) {
            EnjoyConditionResult conditionResult = component.validate(context);
            if (!conditionResult.isEnjoy()) {
                result.setEnjoy(false);
                break;
            }
            // 目前只考虑只有一个层级，如果有多个层级要递归调用validate()
        }

        return result;
    }
}
